package com.lowcode.platform.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 加密工具类
 */
@Component
public class EncryptUtil {

    @Value("${jwt.secret}")
    private String encryptKey;

    /**
     * AES加密
     */
    public String encrypt(String content) {
        if (content == null || content.isEmpty()) {
            return content;
        }
        try {
            AES aes = SecureUtil.aes(encryptKey.getBytes(StandardCharsets.UTF_8));
            return aes.encryptHex(content);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    /**
     * AES解密
     */
    public String decrypt(String encryptedContent) {
        if (encryptedContent == null || encryptedContent.isEmpty()) {
            return encryptedContent;
        }
        try {
            AES aes = SecureUtil.aes(encryptKey.getBytes(StandardCharsets.UTF_8));
            return aes.decryptStr(encryptedContent);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }

    /**
     * MD5加密
     */
    public String md5(String content) {
        return SecureUtil.md5(content);
    }

    /**
     * 生成盐值
     */
    public String generateSalt() {
        return SecureUtil.md5(String.valueOf(System.currentTimeMillis()));
    }
}
